package net.sourceforge.j2meautonetwork.operation;

import net.sourceforge.j2meautonetwork.model.User;
import net.sourceforge.j2meautonetwork.util.CodeDefine;
import net.sourceforge.j2meautonetwork.util.Utilities;

/**
 * 网络管理器,加入超时控制.
 * @author Steven King(woyaoying@hotmail.com)
 * @version 0.9
 */
public class NetworkManager {

    private static NetworkManager instance = null;
    
    private boolean trying = true;

    private NetworkManager() {
    }

    /**
     * 取得唯一实例
     * @return
     */
    public static synchronized NetworkManager getInstance() {
        if (instance == null) {
            instance = new NetworkManager();
        }
        instance.trying = true;
        return instance;
    }

    private boolean tryToConnect(){
        NetworkDetector nd = new NetworkDetector();
        new Thread(nd).start();
        long startime = System.currentTimeMillis();
        low: {
            for (;;) {
                if (!isTrying()) {
                    nd.notifyStop();
                    break low;
                }
                if (nd.getOver()) {
                    if (nd.getConnected()) {
                        Utilities.debug("OKAY");
                        return true;
                    } else {
                        Utilities.debug("FAIL");
                        break low;
                    }
                }
                if ((System.currentTimeMillis() - startime) >= CodeDefine.HTTP_CONNECT_TIME_OUT) {
                    break low;
                }
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        return false;
    }

    private void switchProxy(){
        User.getUser().setProxy(!User.getUser().isProxy());
    }
    
    public boolean tryAllTest(){
        if (!tryToConnect()){
            switchProxy();
            Utilities.debug("Try again " + User.getUser().isProxy());
            return tryToConnect();
        }
        return true;
    }
    
    /**
     * 取消网络连接尝试
     */
    public synchronized void cancelTry(){
        trying = false;
    }
    
    /**
     * 得到当前网络连接状态
     * @return
     */
    public synchronized boolean isTrying(){
        return trying;
    }

}